package com.lcj.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcj.eduService.entity.EduChapter;
import com.lcj.eduService.entity.EduVideo;
import com.lcj.eduService.entity.chapter.ChapterVo;
import com.lcj.eduService.entity.chapter.VideoVo;
import com.lcj.eduService.mapper.EduChapterMapper;
import com.lcj.eduService.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcj.eduService.service.EduVideoService;
import com.lcj.servicebase.config.exceptionHandler.EduException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-14
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    //查询课程大纲列表
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<EduChapter> eduChapterList = baseMapper.selectList(wrapper);
        //查询所有小节
        QueryWrapper wrapperVideo = new QueryWrapper();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> eduVideoList = eduVideoService.list(wrapperVideo);
        //存储最终数据
        List<ChapterVo> finalList = new ArrayList<>();
        //遍历章节集合进行封装
        for(int i=0; i<eduChapterList.size(); i++){
            EduChapter eduChapter = eduChapterList.get(i);
            ChapterVo chapterVo= new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            finalList.add(chapterVo);

            //遍历小节，进行数据封装
            List<VideoVo> videoVoList=new ArrayList<>();
            for(int m=0; m<eduVideoList.size(); m++){
                EduVideo eduVideo = eduVideoList.get(m);
                if(eduVideo.getChapterId().equals(eduChapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }

        return finalList;
    }

    //删除章节
    @Override
    public boolean deleteChapter(String chapterId) {
        //根据chapterId章节，查询小节表，如果查询数据，不进行删除
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        int count = eduVideoService.count(wrapper);
        if(count > 0){
            throw new EduException(2001,"不能删除");
        }else{
            int result = baseMapper.deleteById(chapterId);
            //成功  result > 0
            return result>0;
        }
    }
}
